package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.sun.webkit.graphics.WCRenderQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleRelationServiceImpl implements ApArticleRelationService {

    @Autowired
    ApLikesBehaviorService apLikesBehaviorService;
    @Autowired
    ApUnlikesBehaviorService apUnlikesBehaviorService;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 查询用户文章的点赞\不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        //1.预封装
        HashMap resultMap = new HashMap<>();
        resultMap.put("islike",false);
        resultMap.put("isunlike",false);

        //2.参数校验
        if (dto == null || dto.getArticleId() == null || dto.getEntryId() == null){
            return resultMap;
        }

        //3.查询行为实体 主键
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(), null);
        if (behaviorEntry == null){
            return resultMap;
        }

        //4.查询点赞
        ApLikesBehavior likesBehavior = apLikesBehaviorService.getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApLikesBehavior::getEntryId, behaviorEntry.getId())
                .eq(ApLikesBehavior::getOperation, ApLikesBehavior.Operation.LIKE.getCode()) //点赞
                .eq(ApLikesBehavior::getType, ApLikesBehavior.Type.ARTICLE));//点赞类型
        //判断点赞行为不为空，代表点赞
        if (likesBehavior != null){
            resultMap.put("islike",true);  //点赞
        }

        //查询不喜欢
        ApUnlikesBehavior unlikesBehavior = apUnlikesBehaviorService.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, behaviorEntry.getId())
                .eq(ApUnlikesBehavior::getType, ApUnlikesBehavior.Type.UNLIKE.getCode()));
        //判断不喜欢行为不为空，代表不喜欢
        if (unlikesBehavior != null){
            resultMap.put("isunlike",true); //不喜欢
        }

        //5.返回结果
        resultMap.put("entryId",behaviorEntry.getId());

        return resultMap;
    }
}